#include <sxMassSpringSimulationRecorder.h>

Sx::Simulation::Recording::MassSpringSimulationRecorder::MassSpringSimulationRecorder(const std::shared_ptr<MassSpringSimulation>& simulation, const std::shared_ptr<MassSpringSimulationRecording>& recording) : AbstractRecorder(recording) {
	this->setSimulation(simulation);
}

Sx::Simulation::Recording::MassSpringSimulationRecorder::~MassSpringSimulationRecorder() {}

bool Sx::Simulation::Recording::MassSpringSimulationRecorder::setSimulation(const std::shared_ptr<MassSpringSimulation>& simulation) {
	this->simulation = simulation;
	if ( this->simulation == nullptr || this->simulation.use_count() == 0 ) {
		std::cerr << "[MassSpringSimulationRecorder:setSimulation] Warning: Provided simulation has not been initialized (nullptr)." << std::endl;
		return false;
	}
	else return this->simulation->addListener(this);
}

void Sx::Simulation::Recording::MassSpringSimulationRecorder::postUpdate() {
	AbstractRecorder::processFrame();
}

void Sx::Simulation::Recording::MassSpringSimulationRecorder::onConstruct() {}
void Sx::Simulation::Recording::MassSpringSimulationRecorder::preUpdate() {}
void Sx::Simulation::Recording::MassSpringSimulationRecorder::preRender() {}
void Sx::Simulation::Recording::MassSpringSimulationRecorder::postRender() {}
void Sx::Simulation::Recording::MassSpringSimulationRecorder::onReset() {}
void Sx::Simulation::Recording::MassSpringSimulationRecorder::onPause() {}
void Sx::Simulation::Recording::MassSpringSimulationRecorder::onResume() {}

void Sx::Simulation::Recording::MassSpringSimulationRecorder::onDestroy() {
	/*
	MassSpringSimulationKeyFrame frame;
	MassSpringMeshState meshState;
	for ( unsigned int i = 0; i < this->recording->getFrameCount(); i++ ) {
		this->recording->getFrame(i, frame);
		for ( unsigned int j = 0; j < frame.meshStates.size(); j++ ) {
			frame.meshStates.get(j, meshState);
			meshState.invalidate();
		}
	}
	*/
}

bool Sx::Simulation::Recording::MassSpringSimulationRecorder::processFrame(MassSpringSimulationKeyFrame& frame) {
	if ( this->simulation == nullptr ) {
		std::cerr << "[MassSpringSimulationRecorder:processFrame] Error: Cannot process frame for nullptr simulation." << std::endl;
		std::cerr << "  Internal recording unmodified." << std::endl;
		return false;
	}

	//--------------------------------------------------------------------------
	// Iterate through each of the Mass-Spring meshes in the simulation and
	// retrieve a new meshState to store its data. The mesh state is constructed
	// from a reference to one of the meshes in the simulation.
	//--------------------------------------------------------------------------
	for ( unsigned int i = 0; i < this->simulation->getMeshCount(); i++ ) {
		MassSpringMeshState& meshState = frame.meshStates.getNext();
		meshState.save(this->simulation->getMesh(i));
	}

	return true;
}
